package org.jeecgframework.web.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEngineerServiceI;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.pojo.base.ZyEngineerEntity;
import org.jeecgframework.web.system.pojo.base.ZyEngineerHisEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 工程师
 * @author ZhangYunlong
 * @date 2016-04-18 20:03:05
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyEngineerController")
public class ZyEngineerController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyEngineerController.class);

	@Autowired
	private ZyEngineerServiceI zyEngineerService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工程师列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "zyEngineer")
	public ModelAndView zyEngineer(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_engineer/zyEngineerList");
	}

	/**
	 * @author xiul
	 * 2016-7-1 下午2:46:00
	 * Description 工程师列表页 datagrid 
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyEngineerEntity zyEngineer,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEngineerEntity.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"),Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEngineer, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEngineerService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author xiul
	 * 2016-7-1 下午2:44:30
	 * Description 弹出式 选择工程师页面跳转 - 工程师页面选择父级工程师
	 */
	@RequestMapping(params = "zyEngineersForParentEg")
	public ModelAndView zyEngineers(HttpServletRequest request) {
		String sysUserId = oConvertUtils.getString(request.getParameter("sysUserId"));
		request.setAttribute("params", "sysUserId="+sysUserId);
		return new ModelAndView("com/zybk/zy_engineer/zyChooseEngineersForParentEg");
	}
	
	/**
	 * @author xiul
	 * 2016-7-1 下午2:41:00
	 * Description 弹出式 选择工程师页面跳转 - 工程师页面选择父级工程师 datagrid
	 */
	@RequestMapping(params = "datagridForParentEg")
	public void datagridForParentEg(ZyEngineerEntity zyEngineer,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEngineerEntity.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"),Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
		String sysUserId = oConvertUtils.getString(request.getParameter("sysUserId"));
		if(StringUtil.isNotEmpty(sysUserId)){
			//查询所属组织机构和当前选择的系统用户相同的组织机构下的 工程师,并且不不含 系统用户是当前的用户
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" LEFT(dp.org_code,2) AS org_code ");
			sql.append(" FROM ");
			sql.append(" t_s_user_org uo ");
			sql.append(" LEFT JOIN t_s_depart dp on dp.id = uo.org_id ");
			sql.append(" WHERE uo.user_id = '"+sysUserId+"' ");
			Map<String, Object> map = systemService.findOneForJdbc(sql.toString());
			if(null != map && StringUtil.isNotEmpty(map.get("org_code"))){
				sql = new StringBuffer();
				sql.append(" SELECT ");
				sql.append(" eg.id ");
				sql.append(" FROM ");
				sql.append(" zy_engineer eg ");
				sql.append(" LEFT JOIN t_s_base_user bu ON bu.id = eg.ts_base_user_id ");
				sql.append(" LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID ");
				sql.append(" LEFT JOIN t_s_depart dp ON dp.id = uo.org_id ");
				sql.append(" WHERE ");
				sql.append(" dp.org_code LIKE '"+map.get("org_code")+"%'");
				sql.append(" AND dp.logic_delete = 0 ");
				sql.append(" AND bu.id != '"+sysUserId+"' ");
				List<Map<String, Object>> mapList = systemService.findForJdbc(sql.toString());
				List<String> egIds = new ArrayList<String>();
				for (Map<String, Object> rsMap : mapList) {
					if(null != rsMap){
						egIds.add(rsMap.get("id").toString());
					}
				}
				cq.add(Restrictions.in("id", egIds));
			}
		}
		cq.isNull("parentId");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEngineer, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEngineerService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 添加工程师
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyEngineerEntity zyEngineer, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "工程师["+zyEngineer.getName()+"]添加成功";
		try{
			if(zyEngineer.getParentId().getId().equals("")){
				zyEngineer.setParentId(null);
			}
			String cellPhone = zyEngineer.getCellphone();
			boolean flag = true;
			if(StringUtil.isNotEmpty(cellPhone) && null != zyEngineer.getTsBaseUser()){
				List<TSUser> users = systemService.findByProperty(TSUser.class, "mobilePhone", cellPhone);
				if(null != users){
					if(users.size() == 1){
						if(!users.get(0).getId().equals(zyEngineer.getTsBaseUser().getId())){
							flag = false;
							message = "系统用户已经存在当前手机号";
						}
					}else if(users.size() > 1){
						flag = false;
						message = "系统用户已经存在当前手机号";
					}
				}
			}
			j.setSuccess(flag);
			if(flag){
				zyEngineer.setIsAreaEngineer(zyCommonService.isAreaEngineer(zyEngineer.getTsBaseUser().getId()));
				zyEngineer.setIsDelete("0");
				zyEngineerService.save(zyEngineer);
				ZyEngineerHisEntity zyEngineerHis = new ZyEngineerHisEntity();
				MyBeanUtils.copyBeanNotNull2Bean(zyEngineer, zyEngineerHis);
				zyEngineerHis.setBusId(zyEngineer.getId());
				zyEngineerHis.setDataStatus("create");
				zyEngineerService.save(zyEngineerHis);
				if(StringUtil.isNotEmpty(cellPhone)){
					//更新系统用户的电话
					if(null != zyEngineer.getTsBaseUser() && StringUtil.isNotEmpty(zyEngineer.getTsBaseUser().getId())){
						TSUser user = systemService.get(TSUser.class, zyEngineer.getTsBaseUser().getId());
						String oldPhoneNum = user.getMobilePhone();
						user.setMobilePhone(cellPhone);
						systemService.saveOrUpdate(user);
						systemService.addLog("更新工程师时后台更新关联的系统用户[" + user.getUserName() + "]的手机号，由[" + oldPhoneNum + "]更新为：" + cellPhone, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "工程师["+zyEngineer.getName()+"]添加失败";
			throw new BusinessException(e.getMessage());
		}
		systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新工程师
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyEngineerEntity zyEngineer, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		ZyEngineerEntity t = zyEngineerService.get(ZyEngineerEntity.class, zyEngineer.getId());
		String name = t.getName();
		message = "工程师[" + name + "]更新成功";
		if(zyEngineer.getParentId().getId().equals("")){
			zyEngineer.setParentId(null);
		}
		try {
			boolean flag = true;
			String cellPhone = zyEngineer.getCellphone();
			if(StringUtil.isNotEmpty(cellPhone) && null != zyEngineer.getTsBaseUser()){
				List<TSUser> users = systemService.findByProperty(TSUser.class, "mobilePhone", cellPhone);
				if(null != users){
					if(users.size() == 1){
						if(!users.get(0).getId().equals(zyEngineer.getTsBaseUser().getId())){
							flag = false;
							message = "系统用户已经存在当前手机号";
						}
					}else if(users.size() > 1){
						flag = false;
						message = "系统用户已经存在当前手机号";
					}
				}
			}
			j.setSuccess(flag);
			if(flag){
				zyEngineer.setIsAreaEngineer(zyCommonService.isAreaEngineer(zyEngineer.getTsBaseUser().getId()));
				//如果页面不选择上级工程师,那么父级工程师不为空 但是 id为空串 ,数据库存的是 空串不是null ,外键关联会出问题,所以需要手动置为null
				if(zyEngineer.getParentId() != null && zyEngineer.getParentId().getId().equals("")){
					zyEngineer.setParentId(null);
				}
				MyBeanUtils.copyBeanNotNull2Bean(zyEngineer, t);
				if(null==zyEngineer.getParentId()){
					t.setParentId(null);
				}
				zyEngineerService.saveOrUpdate(t);
				ZyEngineerHisEntity zyEngineerHis = new ZyEngineerHisEntity();
				MyBeanUtils.copyBeanNotNull2Bean(t, zyEngineerHis);
				zyEngineerHis.setDataStatus("update");
				zyEngineerHis.setBusId(zyEngineer.getId());
				zyEngineerService.save(zyEngineerHis);
				TSUser tsUser = new TSUser();
				if(null != zyEngineer.getTsBaseUser() && StringUtil.isNotEmpty(zyEngineer.getTsBaseUser().getId())){
					tsUser = systemService.get(TSUser.class, zyEngineer.getTsBaseUser().getId());
				}
				if(StringUtil.isNotEmpty(cellPhone) && null != tsUser){
					//更新系统用户的电话
					String oldPhoneNum = tsUser.getMobilePhone();
					tsUser.setMobilePhone(cellPhone);
					systemService.saveOrUpdate(tsUser);
					systemService.addLog("更新工程师时后台更新关联的系统用户[" + tsUser.getUserName() + "]的手机号，由[" + oldPhoneNum + "]更新为：" + cellPhone, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
				}
				/*if(null != tsUser){
					//更新系统用户角色
					List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", tsUser.getId());
					if(null != roleUsers && roleUsers.size() > 0){
						for (TSRoleUser tsRoleUser : roleUsers) {
							if(tsRoleUser.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_AREA_ENGINEER)){
								if(!zyEngineer.getIsAreaEngineer()){
									TSRole tsRole = systemService.findUniqueByProperty(TSRole.class, "roleCode",StaticValue.RULE_CODE_THIRDPARTY_ENGINEER);
									tsRoleUser.setTSRole(tsRole);
									systemService.saveOrUpdate(tsRoleUser);
									break;
								}
							}else if(tsRoleUser.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER)){
								if(zyEngineer.getIsAreaEngineer()){
									TSRole tsRole = systemService.findUniqueByProperty(TSRole.class, "roleCode",StaticValue.RULE_CODE_AREA_ENGINEER);
									tsRoleUser.setTSRole(tsRole);
									systemService.saveOrUpdate(tsRoleUser);
									break;
								}
							}
						}
					}
				}*/
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "工程师[" + name + "]更新失败";
			throw new BusinessException(e.getMessage());
		}
		systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-6-24 上午11:57:26
	 * Description 检查电话唯一性
	 * @param param 电话号
	 * @param egId 工程师ID
	 */
	@ResponseBody
	@RequestMapping(params="checkEgCellphoneUnique")
	public ValidForm checkEgCellphoneUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="egId",defaultValue="")String egId
			){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM zy_engineer eg");
		sql.append(" WHERE ");
		sql.append(" eg.cellphone = '"+param+"' ");
		if(StringUtil.isNotEmpty(egId)){
			sql.append(" AND id != '"+egId+"' ");
		}
		sql.append(" AND eg.is_delete = 0 ");
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前手机号已经存在");
		}
		return vf;
	}
	
	/**
	 * @author xiul
	 * 2016-6-24 上午11:57:26
	 * Description 检查身份证号唯一性
	 * @param param 身份证号
	 * @param egId 工程师ID
	 */
	@ResponseBody
	@RequestMapping(params="checkEgIdNumUnique")
	public ValidForm checkEgIdNumUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="egId",defaultValue="")String egId
			){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM zy_engineer eg");
		sql.append(" WHERE ");
		sql.append(" eg.id_num = '"+param+"' ");
		if(StringUtil.isNotEmpty(egId)){
			sql.append(" AND id != '"+egId+"' ");
		}
		sql.append(" AND eg.is_delete = 0 ");
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前身份证号已经存在");
		}
		return vf;
	}
	
	/**
	 * 逻辑删除工程师
	 * 
	 * @return
	 */
	@RequestMapping(params = "dologicDel")
	@ResponseBody
	public AjaxJson dologicDel(ZyEngineerEntity zyEngineer, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyEngineer = systemService.getEntity(ZyEngineerEntity.class, zyEngineer.getId());
		message = "工程师[" + zyEngineer.getName() + "]删除成功";
		try{
			zyEngineer.setIsDelete("1");
			zyEngineerService.saveOrUpdate(zyEngineer);
			ZyEngineerHisEntity zyEngineerHis = new ZyEngineerHisEntity();
			MyBeanUtils.copyBeanNotNull2Bean(zyEngineer,zyEngineerHis);
			zyEngineerHis.setDataStatus("delete");
			zyEngineerHis.setBusId(zyEngineer.getId());
			zyEngineerService.save(zyEngineerHis);
		}catch(Exception e){
			e.printStackTrace();
			message = "工程师[" + zyEngineer.getName() + "]删除失败";
		}
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		return j;
	}

	/**
	 * 工程师新增页面跳转
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyEngineerEntity zyEngineer, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEngineer.getId())) {
			zyEngineer = zyEngineerService.getEntity(ZyEngineerEntity.class, zyEngineer.getId());
			req.setAttribute("zyEngineerPage", zyEngineer);
		}
		return new ModelAndView("com/zybk/zy_engineer/zyEngineer-add");
	}
	/**
	 * 工程师编辑页面跳转
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyEngineerEntity zyEngineer, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEngineer.getId())) {
			zyEngineer = zyEngineerService.getEntity(ZyEngineerEntity.class, zyEngineer.getId());
			req.setAttribute("zyEngineerPage", zyEngineer);
		}
		return new ModelAndView("com/zybk/zy_engineer/zyEngineer-update");
	}
	
	/**
	 * 工程师编辑页面跳转
	 */
	@RequestMapping(params = "goView")
	public ModelAndView goView(ZyEngineerEntity zyEngineer, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEngineer.getId())) {
			zyEngineer = zyEngineerService.getEntity(ZyEngineerEntity.class, zyEngineer.getId());
			req.setAttribute("zyEngineerPage", zyEngineer);
		}
		return new ModelAndView("com/zybk/zy_engineer/zyEngineer-view");
	}
	
	/**
	 * @author xiul
	 * 2017-5-26 上午10:59:58
	 * Description 报表 - 弹出式选择工程师 - 页面跳转
	 */
	@RequestMapping(params="goChooseEgsForIrReport")
	public ModelAndView goChooseEgsForIrReport(HttpServletRequest req){
		String departId = req.getParameter("departId");
		String params = "&departId=" + departId;
		req.setAttribute("params", params);
		return new ModelAndView("com/zybk/zy_engineer/zyChooseEgsForIrReport");
	}
	/**
	 * @author xiul
	 * 2017-5-26 上午10:59:58
	 * Description 报表 - 弹出式选择工程师 - datagrid
	 */
	@ResponseBody
	@RequestMapping(params="datagridForIrReport")
	public void datagridForIrReport(ZyEngineerEntity zyEngineer,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEngineerEntity.class, dataGrid);
		cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"),Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEngineer, request.getParameterMap());
		try{
		//自定义追加查询条件
			String departId = request.getParameter("departId");
			CriteriaQuery ctq = new CriteriaQuery(TSUserOrg.class);
			ctq.setProjection(Property.forName("tsUser.id"));
			ctq.add(Property.forName("tsDepart.id").eq(departId));
			cq.add(Property.forName("tsBaseUser.id").in(ctq.getDetachedCriteria()));
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEngineerService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
}
